﻿using FluentFTP;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Mozhi.Abp.Core.Files
{
    public class FluentFTPFileClient : IFileClient
    {
        private string _host = "";

        private int _port = 21;

        private string _userName = "";

        private string _password = "";

        private string _destPath = "";

        public FluentFTPFileClient(IConfiguration configuration, Guid organizationId)
        {
            LoadConfiguration(configuration);

            _destPath = $"{organizationId}/{DateTime.Now.ToString("yyyyMMdd")}";
            
        }

        public async Task<Tuple<bool, string>> UploadFileAsync(Stream stream, string fileName)
        {
            var ftpClient = GetFluentFTPClient();

            var remotePath = $"{_destPath}/{Guid.NewGuid().ToString()}/{fileName}";

            remotePath = remotePath.Replace("-", "");

            var success = await ftpClient.UploadAsync(stream, remotePath , FtpRemoteExists.Overwrite , true);

            remotePath = success ? remotePath : null;

            return new Tuple<bool, string>(success, remotePath);
        }

        public async Task<Stream> DownloadFileAsync(string remotePath)
        {
            var ftpClient = GetFluentFTPClient();

            Stream result = new MemoryStream();

            await ftpClient.DownloadAsync(result, remotePath);

            return result;
        }


        #region
        private void LoadConfiguration(IConfiguration configuration)
        {
            _host = configuration["File:Setting:Ftp:Host"];

            int.TryParse(configuration["File:Setting:Ftp:Port"], out _port);

            _userName = configuration["File:Setting:Ftp:UserName"];

            _password = configuration["File:Setting:Ftp:Password"];
        }


        private FtpClient GetFluentFTPClient()
        {
            var ftpClient = new FtpClient($"ftp://{_host}", _port, _userName, _password)
            {
                EncryptionMode = FtpEncryptionMode.None,
                DataConnectionType = FtpDataConnectionType.PASV,
                Encoding = Encoding.UTF8
            };

            return ftpClient;
        }

        #endregion
    }
}
